package com.reiuy.controller;


import com.fasterxml.jackson.core.JsonProcessingException;

import com.reiuy.entity.Good;
import com.reiuy.entity.User;
import com.reiuy.service.GoodService;
import com.reiuy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/good")
public class GoodController {

    @Resource
    private UserService userService;

    @Resource
    private GoodService goodService;

    /**
     * 添加商品的控制器
     * @param good
     * @return modelandview
     */
    @RequestMapping("/setgood.do")
    public ModelAndView setGood(Good good,HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        User user = new User();
        String tips = "";

        user.setUsername((String) request.getSession().getAttribute("username"));
        int nums = goodService.setGood(good,user);
        if (nums > 0){
            tips = "新商品添加成功";
            mv.addObject("tips",tips);
            mv.setViewName("goodresult/setgoodresult");
        }else{
            //TODO 如果上传失败之后的结果,并给用户友好的提示
        }
        return mv;
    }

    @RequestMapping("/managegood.do")
    public ModelAndView queryuserGood(User user,HttpServletRequest request) throws JsonProcessingException {
        ModelAndView mv = new ModelAndView();
        user.setUsername((String) request.getSession().getAttribute("username"));
        List<Good> usergoods = goodService.selectGoodbyId(user);
        System.out.println(usergoods);
        mv.addObject("usergoods",usergoods);
        mv.setViewName("good/usergoodlist");
        return mv;
        //TODO 关于此功能的实现,需要通过json传递数据
    }

    @RequestMapping( value = "/deletegood.do",method = RequestMethod.GET,produces = "text/plain;charset=utf-8")
    @ResponseBody
    //这个地方一定要加Body注解,不加的话会被理解成controller返回值中的返回逻辑视图名称
    //只有加了注解才会被理解为是String对象
    public String deleteGood(Good good){
        String msg = "";
        int nums = goodService.deleteGood(good);
        if (nums > 0){
            msg = "删除成功";
        }else {
            msg = "删除失败";
        }
        return msg;
    }


    //显示商城主页
    @RequestMapping("/shopindex.do")
    public ModelAndView showGoods(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        List<Good> allgoods = goodService.selectAllgoods();
        mv.addObject("allgoods",allgoods);
        mv.setViewName("shop/shopindex");
        return mv;
    }

}
